package com.techindata.cacheredis;

import org.apache.log4j.Logger;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author jixiang
 * 
 *         往缓存中存入存入单一值数据
 * 
 * */
public class CachePut {
	static Logger logger = Logger
			.getLogger(CachePut.class.getName());

	
	/**
	 * 
	 * @param key
	 *            String存入的key
	 * @param value
	 *            String存入的值
	 * 默认8小时过期
	 * 
	 * 
	 * */
	public static boolean putCache(String key, String value) {
		return putCache(key,value,CacheInit.EXPIRE);
	}


	/**
	 *
	 * @param key
	 *            String存入的key
	 * @param value
	 *            String存入的值
	 * @param expireSeconds
	 *            int 需要缓存的时间，可以为空
	 *
	 *
	 * */
	public static boolean putCache(String key, String value, int expireSeconds) {
		JedisPool pool = RedisConnectionPool.getPool();
		Jedis jedis = null;

		try {
			jedis = pool.getResource();
			if (expireSeconds != 0) {
				jedis.setex(key, expireSeconds, value);
			} else {
				jedis.set(key, value);
			}
			return true;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return false;
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
	}
	public static String getCache(String key) {
		JedisPool pool = RedisConnectionPool.getPool();
		Jedis jedis = null;

		try {
			jedis = pool.getResource();
			return jedis.get(key);
		} catch (Exception e) {
			return "";
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
	}
	public static boolean putObject(String key, Object value, int expireSeconds) {
		JedisPool pool = RedisConnectionPool.getPool();
		Jedis jedis = null;

		try {
			jedis = pool.getResource();
			if (expireSeconds != 0) {
				jedis.setex(key.getBytes(), expireSeconds, SerializeUtil.serialize(value));
			} else {
				jedis.set(key.getBytes(), SerializeUtil.serialize(value));
			}
			return true;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return false;
		}
		finally{
			RedisConnectionPool.returnResource(pool, jedis);
		}
	}

	public static void main(String[] args) {
		CachePut.putCache("ddr","ff");
		System.out.println(CachePut.getCache("ddr"));
	}
}